import Image
import ImageFilter
import math
import sys
import xlwt
imgpath=sys.argv[1]
xlspath=sys.argv[2]

wb=xlwt.Workbook()
ws=wb.add_sheet("text")
color_index=[(0,0,0),(255,255,255),(255,0,0),(0,255,0),(0,0,255),(255,255,0),(255,0,255),(0,255,255),(128,0,0),(0,128,0),(0,0,128),(128,128,0),(128,0,128),(0,128,128),(192,192,192),(128,128,128),(153,153,255),(153,51,102),(255,255,204),(204,255,255),(102,0,102),(255,128,128),(0,102,204),(204,204,255),(0,0,128),(255,0,255),(255,255,0),(0,255,255),(128,0,128),(128,0,0),(0,128,128),(0,0,255),(0,204,255),(204,255,255),(204,255,204),(255,255,153),(153,204,255),(255,153,204),(204,153,255),(255,204,153),(51,102,255),(51,204,204),(153,204,0),(255,204,0),(255,153,0),(255,102,0),(102,102,153),(150,150,150),(0,51,102),(51,153,102),(0,51,0),(51,51,0),(153,51,0),(153,51,102),(51,51,153),(51,51,51)]

def distance(color_1,color_2):
  return math.sqrt((color_1[0]-color_2[0])*(color_1[0]-color_2[0])+(color_1[1]-color_2[1])*(color_1[1]-color_2[1])+(color_1[2]-color_2[2])*(color_1[2]-color_2[2]))
  #return math.pow(color_1[0]*color_1[0]+color_1[1]*color_1[1]+color_1[2]*color_1[2]-color_2[0]*color_2[0]-color_2[1]*color_2[1]-color_2[2]*color_2[2],2)

def find_simlar(color,color_index):
  dis_min=(-1,255*math.sqrt(3),(255,255,255))
  for color_i, color_d in enumerate(color_index):
    d=distance(color_d,color)
    if d<dis_min[1]:
      dis_min=(color_i,d,color_d)
  return dis_min
img=Image.open(imgpath)
size=img.size
pimg=img.load()
for x in range(size[0]):
  for y in range(size[1]):
    index=find_simlar(pimg[x,y],color_index)[0]
    bgPattern=xlwt.Pattern()
    bgPattern.pattern=xlwt.Pattern.SOLID_PATTERN
    bgPattern.pattern_fore_colour=index
    bgStyle=xlwt.XFStyle()
    bgStyle.pattern=bgPattern
    ws.write(y,x,"",bgStyle)
    ws.col(x).width=300
   
wb.save(xlspath)